package ssdb

import (
	"github.com/seefan/gossdb"
	"github.com/seefan/gossdb/conf"
	"strconv"
	"strings"
	"sync"
)

var (
	mapClient = make(map[string]*gossdb.Connectors,20)// 连接全局对象
	lock sync.Mutex // 连接锁定防止并发访问
)

//获取ssdb连接池
func GetSSdbPool(config map[string]string) (*gossdb.Connectors, error) {
	keyConn := config["ipport"]
	pool, ok := mapClient[keyConn]
	if ok {
		return pool, nil
	}
	lock.Lock()
	defer lock.Unlock()
	/*二次获取防止并发多次连接*/
	pool, ok = mapClient[keyConn]
	if ok {
		return pool, nil
	}
	newPool, err := connect(config)
	if err != nil {
		return nil, err
	}
	mapClient[keyConn] = newPool
	return newPool, nil
}

//获取客户端
func connect(config map[string]string) (*gossdb.Connectors, error) {
	keyConnAry := strings.Split(config["ipport"], ":")
	port, err := strconv.Atoi(keyConnAry[1])
	if err != nil {
		return nil, err
	}
	password, ok := config["password"]
	if !ok {
		password = ""
	}
	minPoolSize := 10
	minPoolSizeStr, ok := config["MinPoolSize"]
	if ok {
		atoi, err := strconv.Atoi(minPoolSizeStr)
		if err == nil {
			minPoolSize = atoi
		}
	}
	maxPoolSize := 200
	maxPoolSizeStr, ok := config["MaxPoolSize"]
	if ok {
		atoi, err := strconv.Atoi(maxPoolSizeStr)
		if err == nil {
			maxPoolSize = atoi
		}
	}
	pool, err := gossdb.NewPool(&conf.Config{
		Host:             keyConnAry[0],
		Port:             port,
		MinPoolSize:      minPoolSize,
		MaxPoolSize:      maxPoolSize,
		AcquireIncrement: 20,
		Password:         password,
		RetryEnabled:     true,
	})

	if err != nil {
		return nil, err
	}
	return pool, nil
}